package com.woniu.rear.comm.sentinel.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.alibaba.csp.ahas.shaded.com.alibaba.acm.shaded.org.codehaus.jackson.map.ObjectMapper;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.woniu.rear.comm.core.code.ResponseEnum;
import com.woniu.rear.comm.core.dto.ResponseEntity;

import lombok.extern.slf4j.Slf4j;

/**
 * ahas统一流控逻辑,SpringBoot上下午启动初始化类
 * @author liwei
 *
 */
@Component
@Slf4j
public class BlockExceptionHandler implements ApplicationRunner {

	@Override
	public void run(ApplicationArguments args) throws Exception {
		//初始化自定义流控逻辑
		WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
			
			private ObjectMapper objectMapper = new ObjectMapper();
			
			@Override
			public void blocked(HttpServletRequest request, HttpServletResponse response, String resouce,BlockException e)
					throws IOException {
				response.setCharacterEncoding("utf8");
				response.setContentType("application/json;charset=utf8");
				ResponseEntity<String> resp = null;
				if(e instanceof DegradeException) {
					log.info("block.degrade: {}",request.getRequestURL());
					resp = new ResponseEntity<>(ResponseEnum.BLOCK_DEGRADE.getCode(), ResponseEnum.BLOCK_DEGRADE.getMsg());
				} else if(e instanceof FlowException) {
					log.info("block.flow: {}",request.getRequestURL());
					resp = new ResponseEntity<>(ResponseEnum.BLOCK_FLOW.getCode(), ResponseEnum.BLOCK_FLOW.getMsg());
				}
				String json = objectMapper.writeValueAsString(resp);
				response.getWriter().write(json);
				response.getWriter().flush();
			}
		});
	}

}
